﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LAVAA.BL.Business;
using LAVAA.DAL;

namespace LAVAA.BL.Control
{
    public class UserFacade
    {
        UnitOfWork _uow = new UnitOfWork();

        public void AddUser(User user, Guid groupId)
        {
            UserManager userMgr = new UserManager(_uow);
            user.UserGroup = _uow.UserGroupRepository.GetById(groupId);
            userMgr.AddUser(user);
            _uow.Commit();
        }

        public void DeleteUser(Guid id)
        {
            UserManager userMgr = new UserManager(_uow);
            userMgr.DeleteUser(id);
            _uow.Commit();
        }

        public void UpdateUser(User user, Guid groupId)
        {
            UserManager userMgr = new UserManager(_uow);
            user.UserGroup = _uow.UserGroupRepository.GetById(groupId);
            userMgr.UpdateUser(user);
            _uow.Commit();
        }

        public IEnumerable<User> FindUsers(string username, string firstname, string lastname, string group)
        {
            return _uow.UserRepository.Find(filter: 
                a => ((!string.IsNullOrEmpty(username)) ?  a.UserId.Contains(username) : true)
                    && ((!string.IsNullOrEmpty(firstname)) ? a.UserId.Contains(firstname) : true)
                    && ((!string.IsNullOrEmpty(lastname)) ? a.UserId.Contains(lastname) : true)
                    && ((!string.IsNullOrEmpty(group)) ? a.UserGroup.Name.Contains(group) : true)
                ).ToList();
        }

        public User FindUser(string username, string firstName)
        {
            return _uow.UserRepository.Find(filter: 
                a => !string.IsNullOrEmpty(username) ?  a.UserId == username : true
                && !string.IsNullOrEmpty(firstName) ? a.FirstName == firstName : true
                ).FirstOrDefault();
        }

        public User FindUserById(Guid id)
        {
            return _uow.UserRepository.Find(filter: a => a.Id == id).FirstOrDefault();
        }
    }
}
